/**   
 * Copyright © 2018 嘉源锐信. All rights reserved.
 * 
 * @Title: ConsumerMessageListener.java 
 * @Project: mq-consumer-client
 * @Package: com.huntkey.rx.sceo.mq.consumer.client.config 
 * @Description: TODO
 * @author: liuyong0   
 * @date: 2018年9月13日 上午10:54:12 
 * @version: V1.0   
 */
package com.amos.mqclient.consumer.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/** 
 * @ClassName: ConsumerMessageListener 
 * @Description: mq消息监听器封装类
 * @author: liuyong0
 * @date: 2018年9月13日 上午10:54:12  
 */
@Component
public class MessageListener {
	
	private static final Logger logger = LoggerFactory.getLogger(MessageListener.class);
	
	@Autowired
	private ConnectionFactory connectionFactory;

    /**
     * 在容器中加入消息监听
     * @param queue
     * @param messageHandler
     * @param isAck
     * @throws Exception
     */
	public void addMessageLister(String queue, MessageHandler messageHandler, boolean isAck) throws Exception {
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(this.connectionFactory);
        container.setQueueNames(queue);
        AcknowledgeMode ack = AcknowledgeMode.NONE;
        if(isAck) {
        	ack = AcknowledgeMode.MANUAL;
        }
        messageHandler.setAck(queue, ack);
        container.setAcknowledgeMode(ack);
        MessageListenerAdapter adapter = new MessageListenerAdapter(messageHandler);
        container.setMessageListener(adapter);
        container.start();
        logger.info("------ 已成功监听异步消息触发通知队列：{} ------", queue);
	}

}
